package com.example.demo;

import javax.annotation.PostConstruct;
import javax.management.MalformedObjectNameException;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

@SpringBootApplication
public class DemoApplication implements ApplicationRunner {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {
		System.out.println("app runner...");
	}

}

@RestController
@Slf4j
@EnableAsync
class TestController {

	@Autowired
	AsyncService as;

	@Autowired
	DataSource ds;

	@PostConstruct
	void init() throws MalformedObjectNameException {

	}

	@GetMapping("test")
//	@Transactional
	Object test() {

		System.out.println(ds.getClass());
		System.out.println(Thread.currentThread().getName());

		as.task1();
		
		System.out.println("test...");

		return "OK";

	}
	
	@GetMapping("ds")
	Object ds() {

		org.apache.tomcat.jdbc.pool.DataSource dSource = (org.apache.tomcat.jdbc.pool.DataSource) ds;
		
		return String.format("active:%s maxActive:%s", dSource.getActive(), dSource.getMaxActive());

	}

	@Scheduled(fixedRate = 1000)
	public void datesourceMonitor() {

		org.apache.tomcat.jdbc.pool.DataSource dSource = (org.apache.tomcat.jdbc.pool.DataSource) ds;
		
		log.info("active:{} maxActive:{}", dSource.getActive(), dSource.getMaxActive());

	}

}
